package pers.ree.demo.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {

    private static final int MAX = 200;


    static class MyForkJoinTask extends RecursiveTask<Integer> {

        private Integer startValue;

        private Integer endValue;


        public MyForkJoinTask(Integer startValue, Integer endValue) {
            this.startValue = startValue;
            this.endValue = endValue;
        }

        @Override
        protected Integer compute() {
            if (endValue - startValue < MAX) {
                System.out.println("startValue="+startValue+", endValue="+endValue);
                Integer totalValue = 0;

                for (int index=startValue; index<=endValue; index++) {
                    totalValue += index;
                }

                return totalValue;
            } else {
                MyForkJoinTask task1 = new MyForkJoinTask(startValue, (startValue + endValue)/2);
                task1.fork();

                MyForkJoinTask task2 = new MyForkJoinTask((startValue + endValue)/2+1, endValue);
                task2.fork();

                return task1.join() + task2.join();
            }
        }
    }

    public static void main(String[] args) {
        long beginTimeMillis = System.currentTimeMillis();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> taskFuture = pool.submit(new MyForkJoinTask(1, 100001));
        try {
            Integer result = taskFuture.get();
            System.out.println("result=" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        long endTimeMillis = System.currentTimeMillis();
        long time = endTimeMillis - beginTimeMillis;
        System.out.println("用时=" + time);
    }
}
